package com.engine.kq.cmd.hrmAttProcSet;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.wfset.attendance.domain.HrmAttProcFields;
import com.engine.kq.wfset.attendance.domain.HrmAttProcSet;
import com.engine.kq.wfset.attendance.manager.HrmAttProcFieldsManager;
import com.engine.kq.wfset.auto.AutoInitWFSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.label.LabelComInfo;
import weaver.workflow.form.FormManager;
import weaver.workflow.workflow.BillComInfo;
import weaver.workflow.workflow.WorkflowBillComInfo;

/**
 * 改变考勤流程设置的信息
 * @author pzy
 *
 */
public class SaveStateProcSetCreateFormCmd extends AbstractCommonCommand<Map<String, Object>>{

  private SimpleBizLogger logger;

  public SaveStateProcSetCreateFormCmd(Map<String, Object> params, User user) {
		this.user = user;
		this.params = params;
  }

  @Override
  public BizLogContext getLogContext() {
    return null;
  }

  @Override
  public List<BizLogContext> getLogContexts() {
    return logger.getBizLogContexts();
  }

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String,Object> retmap = new HashMap<String,Object>();
		 
		List<Object> lsGroup = new ArrayList<Object>();
		Map<String,Object> groupitem = null;
		List<Object> itemlist = null;
		try {
			if(!HrmUserVarify.checkUserRight("HrmAttendanceProcess:setting", user)){
				retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
				return retmap;
			}
      int formid1 = 0;
			
			int field006 = StringUtil.parseToInt(StringUtil.vString(params.get("field006")), 0);
      int usedetail = StringUtil.parseToInt(StringUtil.vString(params.get("usedetail")), 0);
      if(field006 == 5 || field006 == 6 || field006 == 7 || field006 == 8){
        //排班流程默认只有明细
        usedetail = 1;
      }

      String formname = StringUtil.vString(params.get("formName"));
      AutoInitWFSet autoInitWFSet = new AutoInitWFSet();
      autoInitWFSet.setUser(user);
      autoInitWFSet.setLog(false);
      autoInitWFSet.setIsdetail(1==usedetail);
      formid1 = autoInitWFSet.InitForm(""+field006, formname);
//      formid1 = createTable(field006,formname,retmap);

      if(formid1 != 0){
        retmap.put("formId", formid1);
        retmap.put("formName", formname);
        retmap.put("status", "1");
      }

		} catch (Exception e) {
			retmap.put("status", "-1");
			if(e.getMessage().equalsIgnoreCase(SystemEnv.getHtmlLabelName(83791,user.getLanguage()))){
        retmap.put("message",  SystemEnv.getHtmlLabelName(83791,user.getLanguage()));
      }else{
        retmap.put("message",  SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
      }
			writeLog(e);
		}
			
		return retmap;
	}

  /**
   * 生成表单和字段对应关系
   * @param field006
   * @param formname
   * @param retmap
   * @return
   * @throws Exception
   */
  public int createTable(int field006, String formname,Map<String,Object> retmap) throws Exception{
    RecordSet rs = new RecordSet();
    boolean isoracle = rs.getDBType().equals("oracle") ;
    boolean issqlserver = rs.getDBType().equals("sqlserver");

    formname = formname.replaceAll("<","＜").replaceAll(">","＞").replaceAll("'","''");
    formname = Util.toHtmlForSplitPage(formname);
    rs.executeSql("select COUNT(*) from (select t2.labelname from workflow_bill t left join htmllabelinfo t2 on t.namelabel = t2.indexid where t2.labelname = '"+formname+"' union all select formname from workflow_formbase where formname = '"+formname+"') t");
    if(rs.next() && rs.getInt(1) > 0){
      String errorLabel = SystemEnv.getHtmlLabelName(83791, user.getLanguage());
      retmap.put("status", "-1");
      retmap.put("message",  errorLabel);
      return 0;
    }
    FormManager FormManager = new FormManager();
    RecordSetTrans RecordSetTrans = new RecordSetTrans();
    BillComInfo BillComInfo = new BillComInfo();
    LabelComInfo LabelComInfo = new LabelComInfo();
    HrmAttProcFieldsManager attProcFieldsManager = new HrmAttProcFieldsManager();

    String formdes = StringUtil.vString(params.get("formdes"));
    formdes = formdes.replaceAll("<","＜").replaceAll(">","＞").replaceAll("'","''");
    formdes = Util.toHtmlForSplitPage(formdes);
    int subcompanyid = Util.getIntValue(StringUtil.vString(params.get("subcompanyid")),-1);
    int subCompanyId3 = Util.getIntValue(StringUtil.vString(params.get("subcompanyid3")),-1);
    int formid1 = FormManager.getNewFormId();
    String formtable_main = "formtable_main_"+formid1*(-1);
    if(formid1 < -1) {
      HrmAttProcSetLogUtil hrmAttProcSetLogUtil = new HrmAttProcSetLogUtil(user,BizLogType.HRM_ENGINE, BizLogSmallType4Hrm.HRM_ENGINE_HRM_ATT_PROCSET, BizLogSmallType4Hrm.HRM_ENGINE_HRM_ATT_PROCSET);
      String realLogSql = "select *from workflow_billfield where "+Util.getSubINClause(""+formid1, "billid", "in");;
      this.logger = hrmAttProcSetLogUtil.logStateSetLogSql(true, realLogSql, params,"createForm");

      boolean success = false;
      RecordSetTrans.setAutoCommit(false);
      try{
        int namelabelid = -1;
        if(issqlserver) RecordSetTrans.executeSql("select indexid from HtmlLabelInfo where labelname='"+formname+"' collate Chinese_PRC_CS_AI and languageid="+user.getLanguage());
        else RecordSetTrans.executeSql("select indexid from HtmlLabelInfo where labelname='"+formname+"' and languageid="+user.getLanguage());
        if(RecordSetTrans.next()) namelabelid = RecordSetTrans.getInt("indexid");//如果表单名称在标签库中存在，取得标签id
        else{
          namelabelid = FormManager.getNewIndexId(RecordSetTrans);//生成新的标签id
          if(namelabelid!=-1){//更新标签库
            RecordSetTrans.executeSql("delete from HtmlLabelIndex where id="+namelabelid);
            RecordSetTrans.executeSql("delete from HtmlLabelInfo where indexid="+namelabelid);
            RecordSetTrans.executeSql(" insert into HtmlLabelIndex(id,indexdesc)  values("+namelabelid+",'"+formname+"')");
            RecordSetTrans.executeSql(" insert into HtmlLabelInfo(INDEXID,labelname, LANGUAGEID)  values("+namelabelid+",'"+formname+"',7)");
            RecordSetTrans.executeSql(" insert into HtmlLabelInfo(INDEXID,labelname, LANGUAGEID)  values("+namelabelid+",'"+formname+"',8)");
            RecordSetTrans.executeSql(" insert into HtmlLabelInfo(INDEXID,labelname, LANGUAGEID)  values("+namelabelid+",'"+formname+"',9)");
          }
        }
        int minSubId = -1;
        if(subcompanyid==-1){//分权分部的取得。如果页面没有，则首先从分权设置的默认机构取得，如果默认机构没有设置则取所有分部中id最小的那个分部。
          RecordSetTrans.executeSql("select dftsubcomid from SystemSet");
          if(RecordSetTrans.next()) subcompanyid = Util.getIntValue(RecordSetTrans.getString("dftsubcomid"),-1);
          if(subcompanyid==-1){
            RecordSetTrans.executeSql("select min(id) as id from HrmSubCompany");
            if(RecordSetTrans.next()) {
              minSubId = subcompanyid = RecordSetTrans.getInt("id");
            }
          }
        }
        if(subCompanyId3==-1){//分权分部的取得。如果页面没有，则首先从分权设置的默认机构取得，如果默认机构没有设置则取所有分部中id最小的那个分部。
          RecordSetTrans.executeSql("select fmdftsubcomid,dftsubcomid from SystemSet");
          if(RecordSetTrans.next()){
            subCompanyId3 = Util.getIntValue(RecordSetTrans.getString("fmdftsubcomid"),-1);
            if(subCompanyId3 == -1) subCompanyId3 = Util.getIntValue(RecordSetTrans.getString("dftsubcomid"),-1);
          }
          if(subCompanyId3 == -1){
            if(minSubId == -1) {
              RecordSetTrans.executeSql("select min(id) as id from HrmSubCompany");
              if(RecordSetTrans.next()) subCompanyId3 = RecordSetTrans.getInt("id");
            } else {
              subCompanyId3 = minSubId;
            }
          }
        }
        RecordSetTrans.executeSql("insert into workflow_bill(id,namelabel,tablename,detailkeyfield,formdes,subcompanyid,subCompanyId3,from_module_) values("+formid1+",'"+namelabelid+"','"+formtable_main+"','mainid','"+formdes+"','"+subcompanyid+"','"+subCompanyId3+"','hrm_mf')");
        FormManager.createMainForm(formid1,formtable_main);
        RecordSetTrans.commit();

        LabelComInfo.addLabeInfoCache(String.valueOf(namelabelid));
        BillComInfo.addBillCache(""+formid1);
        WorkflowBillComInfo workflowBillComInfo=new WorkflowBillComInfo();
        workflowBillComInfo.addWorkflowBillCache(String.valueOf(formid1));
        success = true;
      }catch(Exception exception){
        exception.printStackTrace();
        success = false;
        RecordSetTrans.rollback();
      }
      //根据已有表单新建表单，需要把原表单的信息复制过来
      if(success){
        int oldformid = Util.getIntValue(String.valueOf(params.get("oldformid")), 0);
        if(oldformid != 0){
          int detachable=Util.getIntValue(String.valueOf(params.get("detachable")),0);
          FormManager.setFormInfoByTemplate(formid1, oldformid,0,user);
        }
      }
      RecordSetTrans = new RecordSetTrans();
      RecordSetTrans.setAutoCommit(false);
      HrmAttProcSet setBean = new HrmAttProcSet();
      setBean.setField006(field006);
      List list = attProcFieldsManager.find("[map]field001:"+setBean.getBillId()+";languageid:"+user.getLanguage());
      //生成主表字段
      String isDecimal = "number\\((\\d+),(\\d+)\\)" ;
      HrmAttProcFields bean = null;
      String fieldname = "";
      String fielddbtype = "";
      for(int i=0; i<list.size(); i++){
        bean = (HrmAttProcFields)list.get(i);
        fieldname = bean.getField002();
        fielddbtype = bean.getField004();
        if(isoracle){
          if("text".equalsIgnoreCase(fielddbtype)) {
            fielddbtype = "varchar2(4000)";
          } else if(fielddbtype.indexOf("varchar(")!=-1) {
            fielddbtype = fielddbtype.replace("varchar(", "varchar2(");
          }
        }else if(DialectUtil.isMySql(rs.getDBType())){
          fielddbtype = fielddbtype.replaceFirst(isDecimal,"decimal($1,$2)") ;
          fielddbtype = fielddbtype.replace("number","bigint").replace("varchar2(","varchar(") ;
        }
        RecordSetTrans.executeSql("alter table "+formtable_main+" add "+fieldname+" "+fielddbtype);
        String insertsql="INSERT INTO workflow_billfield(billid,fieldname,fieldlabel,fielddbtype,fieldhtmltype,type,dsporder,viewtype,detailtable,textheight,textheight_2,childfieldid,imgwidth,imgheight) VALUES ("+formid1+",'"+fieldname+"','"+bean.getField003()+"','"+fielddbtype+"','"+bean.getField005()+"','"+bean.getField006()+"','"+bean.getField009()+"',"+0+",'',null,'',null,null,null)";
        RecordSetTrans.executeSql(insertsql);
      }
      RecordSetTrans.commit();
    }
    return formid1;
  }

}
